package com.freewater.javabase.demo.network.http;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

public class URLConnectionDemo {
    public static void main(String[] args) throws IOException {
        URL url = new URL("https://www.liaoxuefeng.com/wiki/1252599548343744/1319099982413858");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // 设置method
        connection.setRequestMethod("GET");
        connection.setUseCaches(false);
        connection.setConnectTimeout(5000);
        // 设置request headers
        connection.setRequestProperty("Accept", "*/*");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 11; Windows NT 5.1)");
        //
        connection.connect();
        if (connection.getResponseCode() != 200) {
            throw new RuntimeException("Bad response");
        }
        // 获取响应headers
        System.out.println(">>>> headers");
        final Map<String, List<String>> headerFields = connection.getHeaderFields();
        for (Map.Entry<String, List<String>> entry : headerFields.entrySet()) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
        // 获取响应内容
        System.out.println(">>>> content");
        final String contentType = connection.getContentType();
        String charset = "ISO-8859-1";
        if (contentType != null) {
            final int indexStart = contentType.indexOf("charset");
            if (indexStart != -1 ) {
                charset = contentType.substring(indexStart + 8);
            }
        }
        System.out.println(">>>> using charset " + charset);
        try (final InputStream inputStream = connection.getInputStream();
             final InputStreamReader reader = new InputStreamReader(new BufferedInputStream(inputStream), Charset.forName(charset))) {
            int read;
            char[] buffer = new char[1024];
            final StringBuilder contentBuilder = new StringBuilder();
            while ((read = reader.read(buffer)) != -1) {
                contentBuilder.append(buffer, 0, read);
            }
            System.out.println(contentBuilder.substring(0, 200));
        }
    }
}
